package com.smartstate.dataManagement.util;

import com.smartstate.dataManagement.entity.User;
import com.smartstate.dataManagement.eunm.CommonEunm;
import com.smartstate.dataManagement.mapper.UserMapper;
import com.smartstate.dataManagement.service.UserService;
import com.smartstate.dataManagement.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: hhx
 * @Date: 2022/11/14/9:28
 * @Description: 系统管理员初始化
 */
@Component
@Slf4j
public class UserInitUtils implements ApplicationRunner {
    @Autowired
    UserService  userService;
    @Autowired
    UserMapper userMapper;

    @Autowired
    PasswordEncoder passwordEncoder;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        if(!initUser()){
            log.info("添加失败 ，继续添加 ");
            initUser();
        }
    }
    public boolean  initUser(){
        log.info("*********** 系统管理员初始化  ***********************");
        User sqlUser=userMapper.getUserByUsername(CommonEunm.ADMIN_NAME.getValue());
        User user = new User();
        user.setPassword(CommonEunm.ADMIN_PASSWORD.getValue());
        user.setPhone(CommonEunm.ADMIN_PHONE.getValue());
        user.setUserName(CommonEunm.ADMIN_NAME.getValue());
        user.setNickname(CommonEunm.ADMIN_NICK.getValue());
        if(null !=sqlUser){
            if(userMapper.deleteById(sqlUser.getId())>0){
                boolean  result=userService.initAdmin(CommonEunm.ROLE_ID.getValue(), user);
                if(result){
                    log.info("系统管理员初始化成功");
                    return  true;
                }
            }
        }
        else{// 不存在用户，直接创建
            boolean  result=userService.initAdmin(CommonEunm.ROLE_ID.getValue(), user);
            if(result){
                log.info("系统管理员初始化成功");
                return  true;
            }
        }
        return  false;
    }
}
